//
//  Token.m
//  Air
//
//  Created by 林购进 on 17/3/2.
//  Copyright © 2017年 lingoujin. All rights reserved.
//

#import "Token.h"

@implementation Token
+ (Token *)sharedInstance {
    static Token *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [Token new];
        NSData *infoData = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultKeyToken];
        if (infoData) {
            sharedInstance = [NSKeyedUnarchiver unarchiveObjectWithData:infoData];
        }
    });
    return sharedInstance;
}

- (void)archive
{
    NSData *infoData = [NSKeyedArchiver archivedDataWithRootObject:self];
    if (infoData) {
        [[NSUserDefaults standardUserDefaults] setObject:infoData forKey:KUserDefaultKeyToken];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (BOOL)isExpired
{
    //- 86400：判断提前一天过期
    NSDate *expire = [NSDate dateWithTimeIntervalSince1970:[self.expire doubleValue] - 86400];
    return [expire before:[NSDate date]];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.token = [aDecoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(token))];
        self.expire = [aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(expire))];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.token forKey:NSStringFromSelector(@selector(token))];
    [aCoder encodeObject:self.expire forKey:NSStringFromSelector(@selector(expire))];
}
@end
